# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

per_adult_total_empl_income_dt <-
    readRDS("~/estimation-output/unearned_income_effect_estimates_per_adult_total_empl_income_capitalization.rds") #nolint
setnames(per_adult_total_empl_income_dt, "ref_event_time", "event_time")
per_adult_total_empl_income_dt <-
    per_adult_total_empl_income_dt[event_time == 99]

per_adult_labor_tax_and_transfer_dt <-
    readRDS("~/estimation-output/unearned_income_effect_estimates_per_adult_labor_tax_and_transfer_capitalization.rds") #nolint
setnames(per_adult_labor_tax_and_transfer_dt, "ref_event_time", "event_time")
per_adult_labor_tax_and_transfer_dt <- per_adult_labor_tax_and_transfer_dt[event_time == 99]

# Note: above variable defined as transfers - taxes
# so need to multiply by -1
per_adult_labor_tax_and_transfer_dt[, estimate := (-1) * estimate]

implied_consumption_dt <-
    readRDS("~/estimation-output/unearned_income_effect_estimates_implied_consumption_cap_capitalization.rds") #nolint
setnames(implied_consumption_dt, "ref_event_time", "event_time")
implied_consumption_dt <- implied_consumption_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-A.4.tex"
file.create(filedir)

# Start Table A.4
start_latex_table(
    column_structure = "cccccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  & \\multicolumn{6}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 3,
    end_col = 8,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 2 & Quartile 3 & Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & Pre-Win Income  &  Pre-Win Income & Pre-Win Income & Pre-Win Income " #nolint
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & (1) & & (2) & (3) & (4) & (5) " #nolint
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Add body of Table A.4
# - introduce convenience functions given a similar structure throughout

TableA4Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{2}{*}{%s} & & %s & & %s & %s & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 5]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 1]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 2]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 3]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 4]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA4Row2 <- function(dt, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & & (%s) & & (%s) & (%s) & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 5]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 1]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 2]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 3]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 4]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

# Per-Adult Total Labor Earnings
TableA4Row1(
    dt = per_adult_total_empl_income_dt,
    text = "Per-Adult Total Labor Earnings",
    scaler = 1
)
TableA4Row2(
    dt = per_adult_total_empl_income_dt,
    scaler = 1
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Per-Adult Labor Earnings Taxes
TableA4Row1(
    dt = per_adult_labor_tax_and_transfer_dt,
    text = "Per-Adult Labor Earnings Taxes",
    scaler = 1
)
TableA4Row2(
    dt = per_adult_labor_tax_and_transfer_dt,
    scaler = 1
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Implied Consumption Expenditure
TableA4Row1(
    dt = implied_consumption_dt,
    text = "Implied Consumption Expenditure",
    scaler = 1
)
TableA4Row2(
    dt = implied_consumption_dt,
    scaler = 1
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table A.4
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
per_adult_total_empl_income_dt <- NULL
per_adult_labor_tax_and_transfer_dt <- NULL
implied_consumption_dt <- NULL
rm(
    per_adult_total_empl_income_dt,
    per_adult_labor_tax_and_transfer_dt,
    implied_consumption_dt
)